import { defineStore } from "pinia";
import { Dictionary } from "@/api/blade";
import { state } from "vue-tsc/out/shared";

interface DictItem {
  dictKey: string;
  dictValue: string;
  code: string;
  sort: number;
}

const dictList = ["time_space", "ship_land", "tally_type", "out_times", "retreat_type"];

export const useDictInfo = defineStore("dictInfo", {
  state: () => ({
    dictInfoMap: new Map<string, Array<DictItem>>()
  }),
  getters: {
    getDictInfoList: state => {
      return state;
    }
  },
  actions: {
    initAllDict() {
      const that = this;
      for (const code of dictList) {
        Dictionary({ code: code }).then((res: any) => {
          if (res.data) {
            const list = res.data.sort((n1: DictItem, n2: DictItem) => {
              return n1.sort - n2.sort;
            }) as DictItem[];
            this.dictInfoMap.set(code, list);
          }
        });
      }
    },
    getDictByCode(paramCode: string): any {
      if (this.dictInfoMap.has(paramCode)) {
        return this.dictInfoMap.get(paramCode) as DictItem[];
      }
      Dictionary({ code: paramCode }).then((res: any) => {
        if (res.data) {
          const list = res.data.sort((n1: DictItem, n2: DictItem) => {
            return n1.sort - n2.sort;
          }) as DictItem[];
          this.dictInfoMap.set(paramCode, list);
          return list;
        }
      });
    },
    clearAllDict() {
      this.dictInfoMap.clear();
    }
  }
});
